/* eslint-disable */
import Vue from 'vue';
import sa from './sa'

let zm={introduce:'斩碎21年的梦'};

// ======================= 常用方法 ===========================

(function(){
	let me=zm
	const vm=Vue.prototype

	me.ok=function(text){
		vm.$message.success(text)
	}

	me.error=function(text){
		vm.$message.error(text)
	}

	me.notice=function () {
		//console.log(vm)

	}

	// 打开登录页面
    me.openLogin = function () {
        layer.closeAll();
		return vm.sa_admin.openLogin();
    }

	// 打开登录页面
	me.open403 = function () {
		return vm.sa_admin.open403();
	}

	//处理图片路径
	me.handleImgPath=function (url){
		return location.protocol+'//'+location.host+'/pic'+url;
	}
})();

// ======================= 鉴权 ===========================
(function(){
	let me=zm
	const vm=Vue.prototype

	me.checkAuth=function (perm) {
		let permList=sa.keyListGet('permissionList')
		return permList.includes(perm)
	}

	me.checkModuleAuth=function (perm){
		let permList=sa.keyListGet('permissionList')
		//如果是包含整个模块的权限（如user），直接放行，不去比有没有user:list的权限了
		if(permList.includes(perm)){
			return true;
		}else if(perm.slice(-5)!==':list'){//如果只包含模块的部分权限（如user:List和user:add），那就比有没有初始化列表的权限，有则放行
			perm=perm+':list'
		}
		//console.log(perm)
		return permList.includes(perm)
	}
})();

// ======================= 文件操作 ===========================
(function (){
	let me=zm
	
	//单个上传
	me.uploadFunc=function (url,callback){
		console.log("进");
		// 创建input
		var fileInput = document.createElement("input"); //创建input
		fileInput.type = "file"; //设置类型为file
		fileInput.id = 'uploadfile-' + randomString(12);
		//fileInput.style.display = 'none';
		fileInput.onchange = function(evt) {//绑定onchange事件，选择完文件确定后开始上传
			let file=evt.target.files[0]
			const isLt100M = file.size / 1024 / 1024 < 100;
			if(isLt100M){
				me.startUpload(file, url, callback);
			}else{//大小限制
				callback({code:'100'})
			}
		}
		// 添加到body，并主动触发其点击事件
		document.body.appendChild(fileInput);
		document.querySelector('#' + fileInput.id).click();
	}

	//批量上传
	me.batchUpload=function(url,callback){
		// 创建input
		let fileInput = document.createElement("input"); //创建input
		fileInput.type = "file"; // 设置类型为file
		fileInput.multiple = "multiple"; // 多选
		fileInput.id = 'uploadfile-' + randomString(12);
		//fileInput.style.display = 'none';
		fileInput.onchange = function(evt) {
			// 开始上传
			let files = evt.target.files;
			for (let i = 0; i < files.length; i++) {
				let file=evt.target.files[i]
				const isLt100M = file.size / 1024 / 1024 < 100;
				if(isLt100M){
					me.startUpload(file, url, callback);
				}else{
					callback({code:'100'})//一个超过100，全部return
					return;
				}
			}
		}
		// 添加到body，并触发其点击事件
		document.body.appendChild(fileInput);
		document.querySelector('#' + fileInput.id).click();
	}

	/**
	 * 
	 * @param {请求地址} url 
	 * @param {携带数据} data 
	 * @param {请求类型} type 
	 */
	me.download=function(url,data,type){
		let form=document.createElement('form');
		if(data instanceof Object){//为表单添加数据
			for(let key in data){
				let input=document.createElement('input')
				input.name=key;
				input.value=data[key]
				form.appendChild(input)
			}
		}
        form.style.display = 'none';
        form.method = type || "POST";//请求方式
        form.action = url; //下载文件地址
        document.body.appendChild(form);
        form.submit();
        document.body.removeChild(form);
	}

	// 开始上传
	me.startUpload=function(file, url, callback) {
		// 准备参数
		var form = new FormData();
		form.append('file', file);
		console.log(form);
		// 开始上传
		$.ajax({
			url: url,
			data: form,
			processData: false, // 默认true，设置为 false，不需要进行序列化处理
			cache: false, 		// 设置为false将不会从浏览器缓存中加载请求信息
			contentType: false, // 避免服务器不能正常解析文件
			dataType: 'json',
			type: 'post',
			beforeSend: function (xhr) {
				let token = localStorage.getItem('token')
				if (token){
					let t = JSON.parse(token)
					xhr.setRequestHeader(t.tokenName, t.tokenValue);
				}
				show_jdt();
			},
			complete: function (xhr) {
				close_jdt();
			},
			xhr: xhrOnProgress(function(e) {
				var percent = e.loaded / e.total; // 计算进度百分比, 取值结果为 0~1 之间的小无限不循环小数
				// progressCB(percent * 100);
				set_jdt_value(percent * 100);
				// console.log('进度百分比' + percent);
			}),
			success: function(res) {
				console.log(res)
				callback(res);	// 把地址给回调函数
			},
			error: function(e) {
				window.sa.alert('异常: ' + JSON.stringify(e));
			}
		});
	}
	// ======================= 文件工具方法 ===========================
	// 返回后缀名
	me.get_suffix = function get_suffix(filename) {
		var pos = filename.lastIndexOf('.'); 
		let suffix=''
		if (pos !== -1) {
			suffix = filename.substring(pos + 1);
		}
		return suffix;
	}

	// 返回带有上传回调功能的 xhr
	function xhrOnProgress(fun) {
		xhrOnProgress.onprogress = fun; //绑定监听
		//使用闭包实现监听绑
		return function() {
			//通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
			var xhr = $.ajaxSettings.xhr();
			//判断监听函数是否为函数
			if (typeof xhrOnProgress.onprogress !== 'function')
				return xhr;
			//如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
			if (xhrOnProgress.onprogress && xhr.upload) {
				xhr.upload.onprogress = xhrOnProgress.onprogress;
			}
			return xhr;
		}
	}

	//生成随机字符串
	function randomString(len) {
		　　len = len || 32;
		　　var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
		　　var maxPos = $chars.length;
		　　var str = '';
		　　for (let i = 0; i < len; i++) {
		　　　　str += $chars.charAt(Math.floor(Math.random() * maxPos));
		　　}
		　　return str;
	}
	// ======================= 进度条相关 ===========================
	// 显示进度条
	function show_jdt() {
		close_jdt();	// 先清除原来的
		// 创建节点并添加到body
		var str = '' +
			'<div class="jdt-fox" style="z-index: 999999999; width: 500px; height: 20px; position: fixed; top: calc(50% - 5px); left: calc(50% - 250px); ">'+
			'	<div class="jdt-fox2" style="width: calc(100% - 100px); height: 6px; margin-top: 7px; border-radius: 3px; float: left; background-color: #FFF; box-shadow: 0 0 10px #aaa;">'+
			'		<div class="jdt-fox-value" style=" transition: all 0.1s; position: relative; width: 0.0%; height: 100%; border-radius: 3px; background-color: green; box-shadow: 0 0 10px green;">'+
			'			<div class="jdt-fox-yh" style="position: absolute; right: -10px; top: -5px;">'+
			'				<div style="transition: all 1s; background-color: green; width: 16px; height: 16px; border-radius: 50%;"></div>'+
			'			</div>'+
			'		</div>'+
			'	</div>'+
			'	<div class="jdt-value-text" style="float: left; font-size: 14px; margin-left: 14px; color: #111;"> 0.0% </div>'+
			'</div>';
		var div = document.createElement("div");
		div.innerHTML = str;
		div.className = "jdt-box";
		document.body.appendChild(div);
		// 开启圆点的呼吸动画效果
		if (window.my_interval_index) {
			clearInterval(window.my_interval_index);
		}
		window.my_interval_index = setInterval(function() {
			if (window.one_num === undefined) {
				window.one_num = 0;
			}
			window.one_num++;
			var n_px = window.one_num % 2 == 0 ? '0px' : '20px';
			var box_shadow = "0 0 " + n_px + " green";
			document.querySelector('.jdt-fox-yh div').style.boxShadow = box_shadow;
		}, 1000);
	}

	// 关闭进度条
	function close_jdt() {
		// 先关闭动画
		if (window.my_interval_index) {
			clearInterval(window.my_interval_index);
		}
		// 再销毁dom
		var box = document.querySelector('.jdt-box');
		if (box) {
			box.parentNode.removeChild(box);
		}
	}

	// 设置进度条进度, 参数为一个0~100之间的小数
	function set_jdt_value(value) {
		value = parseInt(value * 10) / 10.0 + '%';	// 保证小数点后一位
		// 改变进度条宽度
		var dft = document.querySelector('.jdt-fox-value');
		if(dft){
			dft.style.width = value;
		}
		// 改变文字百分比值
		var dvt = document.querySelector('.jdt-value-text');
		if(dvt) {
			dvt.innerHTML = value;
		}
		// console.log(value);
	}
})();

// ===========================  websocket相关   =======================================
(function () {

	/**
	 * 对WebSocket的封装, 实现了心跳，以及断线重连
	 *
	 * @param {"ws"|"wss"} ws_protocol 协议
	 * @param {String} ip Ip地址
	 * @param {Number} port 端口
	 * @param {Object} param url参数
	 * @param {function} handler 回调函数
	 * {
	 *     new function (){
	 *         this.onopen(ev,ws)=>{
	 *         }
	 *         this.onmessage(ev,ws)=>{
	 *         }
	 *         this.onclose(ev,ws)=>{
	 *         }
	 *         this.onerror(ev,ws)=>{
	 *         }
	 *         this.ping(ws)=>{
	 *         }
	 *     }
	 * }
	 * @param {number} heartbeatTimeout 心跳超时时间，心跳发送时间为超时时间的一半 毫秒
	 * @param {number} reconnectInterval 断线重联时间间隔 毫秒
	 * @param {"arraybuffer" | "blob"} binaryType 传输数据类型
	 */
	zm.createWS = function (ws_protocol, ip, port,
							param,
							handler,
							heartbeatTimeout,
							reconnectInterval,
							binaryType) {
		this.reconnFlag = true
		// 重连次数
		this.reconnCount = 0
		this.ip = ip;
		this.port = port;
		this.url = ws_protocol + '://' + ip + ':' + port
		this.binaryType = binaryType || 'arraybuffer'

		if (param) {
			this.url += '?user_id=' + param
		}
		console.log(this.url);
		this.handler = handler
		this.heartbeatTimeout = heartbeatTimeout
		this.reconnInterval = reconnectInterval

		this.lastInteractionTime = function () {
			if (arguments.length === 1) {
				this.lastInteractionTimeValue = arguments[0]
			}
			return this.lastInteractionTimeValue
		}

		this.heartbeatSendInterval = heartbeatTimeout / 2

		this.connect = function () {
			let _url = this.url;
			let ws = new WebSocket(_url)

			this.ws = ws

			ws.binaryType = this.binaryType; // 'arraybuffer'; // 'blob' or 'arraybuffer';//arraybuffer是字节
			let self = this
			ws.onopen = function (event) {
				self.reconnCount = 0
				self.handler.onopen.call(self.handler, event, ws)
				self.lastInteractionTime(new Date().getTime())

				self.pingIntervalId = setInterval(function () {
					self.ping(self)
				}, self.heartbeatSendInterval)
			}
			ws.onmessage = function (event) {
				self.handler.onmessage.call(self.handler, event, ws)
				self.lastInteractionTime(new Date().getTime())
			}
			ws.onclose = function (event) {
				clearInterval(self.pingIntervalId) // clear send heartbeat task
				try {
					self.handler.onclose.call(self.handler, event, ws)
				} catch (error) {
				}
				if (self.reconnFlag) {
					self.reconnect(event)
				}
			}
			ws.onerror = function (event) {
				self.handler.onerror.call(self.handler, event, ws)
			}
			return ws
		}

		this.reconnect = function (event) {
			layer.msg('第' + this.reconnCount++ + '次重连...')
			let self = this
			setTimeout(function () {
				self.ws = self.connect()
			}, self.reconnInterval)
		}

		this.ping = function () {
			let iv = new Date().getTime() - this.lastInteractionTime(); // 已经多久没发消息了
			// 单位：秒
			if ((this.heartbeatSendInterval + iv) >= this.heartbeatTimeout) {
				this.handler.ping(this.ws)
			}
		};

		this.send = function (data) {
			this.ws.send(data);
		};
		// 关闭连接，并不在重连
		this.close = function () {
			this.reconnFlag = false
			clearInterval(this.pingIntervalId)
			this.ws.close()
		}
	}
})();


export default zm